package com.demo.gateway.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.gateway.pojo.GatewayRouteDO;
import com.demo.gateway.service.AbstractDynamicGatewayRoute;
import com.demo.gateway.util.JsonUtil;
import com.demo.gateway.vo.core.DataVO;
import com.demo.gateway.vo.core.PageVO;
import com.demo.gateway.vo.core.ReturnVO;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: demo
 * @date: 2020年7月3日
 * @Document : 动态路由实现类
 */
@Slf4j
@Service
public class DynamicGatewayRouteServcie extends AbstractDynamicGatewayRoute {
	/**
	 * redis服务类
	 */
	@Autowired
	private RedisRouteService redisRouteService;

	@Autowired
	private DatabaseRouteServcie databaseRouteServcie;

	@Override
	public PageVO<GatewayRouteDO> queryAllGatewayRoutes() {
		PageVO<GatewayRouteDO> pageVO = new PageVO<GatewayRouteDO>();
		List<GatewayRouteDO> routeBeans = redisRouteService.queryRedisRoutes();
		pageVO.setMsg("查询路由列表成功");
		pageVO.setResults(routeBeans);
		pageVO.setSuccess(true);
		return pageVO;
	}

	@Override
	public ReturnVO addRoute(GatewayRouteDO route, boolean effect) {
		try {
			String routeDefinitionStr = JSONObject.toJSONString(route);
			RouteDefinition routeDefinition = JSON.parseObject(routeDefinitionStr, RouteDefinition.class);
			Route.async(routeDefinition);
		} catch (IllegalStateException e) {
			return ReturnVO.fail("网关路径配置错误[" + e.getMessage() + "]:[" + route.getUri() + "]");
		} catch (IllegalArgumentException e) {
			return ReturnVO.fail("网关URI配置错误[" + e.getMessage() + "]:[" + route.getUri() + "]");
		} catch (Exception e) {
			log.error("解析错误==>", e);
			return ReturnVO.fail("网关参数配置错误:" + e.getMessage());
		}
		log.info("route json==>{}", JsonUtil.toString(route));
		String opsMsg = databaseRouteServcie.addOrUpdateRoute(route);
		redisRouteService.addRedisRoute(route.getId(), JSONObject.toJSONString(route));
		if (effect) {
			this.refreshRoute();
		}
		return ReturnVO.ok(opsMsg);
	}

	@Override
	public ReturnVO deleteRoute(String id) {
		databaseRouteServcie.deleteRoute(id);
		redisRouteService.deleteRedisRoute(id);
		this.refreshRoute();
		return ReturnVO.ok("网关删除成功!");
	}

	@Override
	public DataVO<JSONArray> getGatewayInfo() {
		JSONArray results = redisRouteService.queryRedisRoute();
		return DataVO.ok("获取redis路由成功!", results);
	}

	@Override
	public ReturnVO addRoutes(List<GatewayRouteDO> routes) {
		routes.forEach((route) -> {
			addRoute(route, false);
		});
		this.refreshRoute();
		return ReturnVO.ok("网关批量添加成功!");
	}

	@Override
	public ReturnVO database2Redis() {
		try {
			List<GatewayRouteDO> routeBeans = databaseRouteServcie.queryDatabaseRoutes();
			log.debug("查询路由信息==>{}",routeBeans.size());
			if (routeBeans == null || routeBeans.size() == 0) {
				return ReturnVO.ok("无网关信息需要同步");
			} else {
				redisRouteService.addRedisRoutes(routeBeans);
				return ReturnVO.ok("同步网关信息完成");
			}
		} catch (Exception e) {
			log.error("同步路由信息异常!!!", e);
			return ReturnVO.fail("同步网关信息异常==>" + e.getMessage());
		}
	}
}
